using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using Domain.Entities;
using Domain.Permissions;
using Domain.Services;
using Domain.Misc;

namespace UserInterface.RSS
{
    public partial class Index : RSSPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/xml";
            XmlTextWriter xmlTextwriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
            xmlTextwriter.WriteStartDocument();

            // <rss>
            xmlTextwriter.WriteStartElement("rss");
            xmlTextwriter.WriteAttributeString("version", "2.0");

            // <channel>
            xmlTextwriter.WriteStartElement("channel");
            xmlTextwriter.WriteElementString("title", BoardSettingsManager.Instance.Settings.BoardName);
            xmlTextwriter.WriteElementString("link", "http://" + Request.ServerVariables["HTTP_HOST"] + "/Index.aspx");
            xmlTextwriter.WriteElementString("description", "Forum Index RSS");
            xmlTextwriter.WriteElementString("copyright", "Madboard. All rights reserved.");

            // <item>'s
            IList<Category> categories = CategoryService.GetAll();
            foreach(Category category in categories)
            {
                IList<Forum> forums = ForumService.GetByCategory(category);
                foreach (Forum forum in forums)
                {
                    ForumPermissionManager forumPermissionManager = PermissionManager.CreateForumPermissionManager(forum);
                    if (forumPermissionManager.Read)
                    {
                        // <item>
                        xmlTextwriter.WriteStartElement("item");
                        xmlTextwriter.WriteElementString("title", forum.Name);
                        xmlTextwriter.WriteElementString("description", "Number of topics:" + forum.NumberOfTopics + " Number of replies:" + forum.NumberOfReplies);
                        xmlTextwriter.WriteElementString("link", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ViewForum.aspx?forumId=" + forum.Id);
                        xmlTextwriter.WriteElementString("pubDate", DateTime.Now.ToString("R"));
                        xmlTextwriter.WriteEndElement();
                    }
                }
            }

            // </channel>
            xmlTextwriter.WriteEndElement();

            // </rss>
            xmlTextwriter.WriteEndElement();

            xmlTextwriter.WriteEndDocument();
            xmlTextwriter.Flush();
            xmlTextwriter.Close();
        }
    }


}
